<template>
  <div>
    <el-card>
      <el-alert title="注意：只能为第三级分类设置参数" type="warning" close-text="知道了" />

      <el-cascader
        v-model="selectedKeys"
        clearable
        :options="optionsList"
        separator=" > "
        :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }"
        @change="changeSelected"
      />

      <el-tabs v-model="activeName" @tab-click="selectActiveName">
        <el-button class="addButton" size="medium" :disabled="isDisable" type="primary" @click="showAddAttrsDialog">
          增加参数
        </el-button>
        <el-tab-pane label="静态参数" name="static">
          <el-table :data="staticData" border style="width: 100%" type="expand">
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag v-if="scope.row.val" type="primary">
                  {{ scope.row.val }}
                </el-tag>
                <div v-else>
                  暂无数据
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="参数名称" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleAttrsDel(scope.row)">删除</el-button>
                <el-button type="primary" size="small" @click="handleAttrsEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="动态参数" name="dynamic">
          <el-table :data="dynamicData" border style="width: 100%" type="expand">
            <el-table-column type="expand">
              <template #default="scope">
                <el-tag
                  v-for="(t,i) in scope.row.val"
                  :key="i"
                  type="primary"
                  closable
                  @close="handleCloseTag(scope.row,i)"
                >
                  {{ t }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model="scope.row.inputValue"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 新增属性值
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="参数名称" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleAttrsDel(scope.row)">删除</el-button>
                <el-button type="primary" size="small" @click="handleAttrsEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 增加属性值弹框 -->
    <el-dialog
      :title="'新增'+ titleDialog"
      :visible.sync="addAttrsVisible"
      width="30%"
      :before-close="handleAddAttrsClose"
    >
      <el-form
        ref="addAttrsFormRef"
        :model="addAttrsForm"
        :rules="addAttrsRules"
        label-width="100px"
        class="addAttrsForm"
      >
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="addAttrsForm.name" />
        </el-form-item>
        <el-form-item label="参数值" prop="val">
          <el-input v-model="addAttrsForm.val" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddAttrsClose">取 消</el-button>
        <el-button type="primary" @click="addAttrsSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性值弹框 -->
    <el-dialog
      :title="'修改'+ titleDialog"
      :visible.sync="editAttrsVisible"
      width="30%"
      :before-close="handleEditAttrsClose"
    >
      <el-form
        ref="editAttrsFormRef"
        :model="editAttrsForm"
        :rules="editAttrsRules"
        label-width="100px"
        class="editAttrsForm"
      >
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="editAttrsForm.name" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleEditAttrsClose">取 消</el-button>
        <el-button type="primary" @click="editAttrsSubmit">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { cate, getCateAttrs } from '@/api/category'
import { addAttrs, editAttrs, delAttrs } from '@/api/attr'

export default {
  name: 'AttrList',
  data() {
    return {
      selectedKeys: [],
      optionsList: [],
      activeName: 'static',
      staticData: [],
      dynamicData: [],
      addAttrsVisible: false,
      editAttrsVisible: false,
      addAttrsForm: {
        name: '',
        id: '',
        cid: '',
        _type: '',
        val: ''
      },
      editAttrsForm: {
        name: ''
      },
      addAttrsRules: {
        name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editAttrsRules: {
        name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    titleDialog() {
      if (this.activeName === 'static') {
        return '静态参数'
      } else {
        return '动态参数'
      }
    },
    isDisable() {
      if (this.selectedKeys.length < 3) {
        return true
      } else {
        return false
      }
    }
  },
  mounted() {
    this.getCategory()
  },
  methods: {
    // 获取商品三级分类
    async getCategory() {
      const res = await cate()
      if (res.code !== 200) return this.$message.error('获取分类数据失败！')
      this.optionsList = res.data
    },
    // 级联选择框选中的回调
    changeSelected() {
      this.staticData = []
      this.dynamicData = []
      if (this.selectedKeys.length < 3) return
      this.getAttrListData()
    },
    // 选择的标签栏
    selectActiveName() {
      if (this.activeName === 'static' && this.staticData.length > 1) return
      if (this.activeName === 'dynamic' && this.dynamicData.length > 1) return
      if (this.selectedKeys.length !== 3) {
        this.$message.warning('请先选择商品分类！')
        return
      }
      this.getAttrListData()
    },
    // 获取属性值数据
    async getAttrListData() {
      const res = await getCateAttrs(this.selectedKeys[2], this.activeName)
      if (res.code !== 200) return this.$message.error('获取商品参数数据失败！')
      if (this.activeName === 'static') {
        this.staticData = res.data.attrs_static_list
      } else {
        res.data.attrs_dynamic_list.forEach(item => {
          item.val = item.val ? item.val.split(',') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.dynamicData = res.data.attrs_dynamic_list
      }
    },
    // 增加参数弹框
    showAddAttrsDialog() {
      this.addAttrsVisible = true
    },
    // 关闭新增参数弹框的回调
    handleAddAttrsClose() {
      this.addAttrsVisible = false
      this.$refs.addAttrsFormRef.resetFields()
    },
    // 新增参数弹框确定按钮的回调
    addAttrsSubmit() {
      const addData = {
        name: this.addAttrsForm.name,
        val: this.addAttrsForm.val,
        cid: this.selectedKeys[2],
        _type: this.activeName === 'static' ? 0 : 1
      }
      this.addAttrsHandle(addData)
      this.$nextTick(() => {
        this.getAttrListData()
        this.handleAddAttrsClose()
      }, 1000)
    },
    // 新增参数的函数
    async addAttrsHandle(addData) {
      const res = await addAttrs(addData)
      if (res.code !== 201) return this.$message.error('新增商品参数数据失败！')
      this.$message.success('新增商品参数数据成功！')
    },
    // 展现出输入框的回调
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加tag标签的回调
    async handleInputConfirm(row) {
      const inputValue = row.inputValue
      if (inputValue) {
        row.val.push(inputValue)
      }
      row.inputVisible = false
      row.inputValue = ''
      const addValData = {
        name: row.name,
        cid: row.cid,
        type: row.type,
        val: row.val.join(',')
      }
      const res = await editAttrs(row.id, addValData)
      if (res.code !== 200) return this.$message.error('新增参数值失败！')
      this.$message.success('新增参数成功！')
      this.getAttrListData()
    },
    // 删除tag标签的问题
    async handleCloseTag(row, index) {
      console.log(row)
      row.val.splice(index, 1)
      const delValData = {
        name: row.name,
        cid: row.cid,
        _type: row.type,
        val: row.val.join(',')
      }
      const res = await editAttrs(row.id, delValData)
      if (res.code !== 200) return this.$message.error('删除参数值失败！')
      this.$message.success('删除参数值成功！')
      this.getAttrListData()
    },
    // 删除属性回调
    async handleAttrsDel(row) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((e) => e)
      if (res === 'cancel') return this.$message.info('已取消删除操作！')
      const result = await delAttrs(row.id)
      if (result.code !== 200) return this.$message.info('删除属性失败！')
      this.$message.success('删除属性成功！')
      this.getAttrListData()
    },
    // 修改属性回到
    async handleAttrsEdit(row) {
      this.editAttrsVisible = true
      this.editAttrsForm.name = row.name
      this.editAttrsForm.id = row.id
      this.editAttrsForm.cid = row.cid
      this.editAttrsForm._type = row.type
      this.editAttrsForm.val = Object.prototype.isPrototypeOf.call(Array, row.val) ? row.val : row.val.join(',')
    },
    // 编辑弹框确定的按钮
    async editAttrsSubmit() {
      const res = await editAttrs(this.editAttrsForm.id, this.editAttrsForm)
      if (res.code !== 200) return this.$message.error('修改参数值名称失败！')
      this.$message.success('修改参数值名称成功！')
      this.getAttrListData()
      this.handleEditAttrsClose()
    },
    // 编辑属性弹框关闭的回调
    handleEditAttrsClose() {
      this.editAttrsVisible = false
      this.$refs.editAttrsFormRef.resetFields()
    }
  }
}
</script>

<style scoped>
.el-cascader {
  margin-top: 10px;
  width: 300px;
}

.el-tabs {
  margin-top: 20px;
}

.addButton {
  margin: 10px 0;
}

.el-tag {
  margin: 0 10px;
}

.input-new-tag {
  width: 80px;
}
</style>
